// auth.service.ts
import { Injectable } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  Router
} from '@angular/router';
import { Observable } from 'rxjs';
import { getStore } from '@/utils';
@Injectable({
  providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
  constructor(private router: Router) {}

  canActivate(
    next: any,
    state: RouterStateSnapshot
  ):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    // 在这里写入你的认证逻辑
    const isLoggedIn = getStore({ name: 'userInfo' }).token || false;
    // 获取路由参数
    const param = next.queryParams;

    if (isLoggedIn) {
      // 用户已登录，允许访问路由
      return true;
    } else {
      console.log('next._routerState');
      if (next._routerState.url.indexOf('invited') !== -1) {
        this.router.navigate(['/login'], { queryParams: param });
        return true;
      } else {
        // 如果用户未登录，重定向到登录页面
        this.router.navigate(['/login']);
        // 用户未登录，重定向到登录页面
        return false;
      }
    }
  }
}
